import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { Color, ColorScheme, ColorPickerMode, ColorSchemeType } from '@/types';
import { ColorUtils } from '@/utils/color';
import { StorageService } from '@/services/storage';
import { generateId } from '@/utils';

// 色彩状态接口
interface ColorState {
  // 当前状态
  currentColor: Color;
  selectedColors: Color[];
  activePalette: ColorScheme | null;
  pickerMode: ColorPickerMode;
  isLoading: boolean;
  error: string | null;
  
  // 历史记录
  colorHistory: Color[];
  recentSchemes: ColorScheme[];
  
  // 动作
  setCurrentColor: (color: Color | string) => void;
  addSelectedColor: (color: Color) => void;
  removeSelectedColor: (index: number) => void;
  updateSelectedColor: (index: number, color: Color) => void;
  clearSelectedColors: () => void;
  
  // 调色板操作
  createPalette: (name: string, type: ColorSchemeType) => Promise<ColorScheme>;
  loadPalette: (palette: ColorScheme) => void;
  savePalette: (palette: ColorScheme) => Promise<void>;
  deletePalette: (id: string) => Promise<void>;
  
  // 颜色历史
  addToHistory: (color: Color) => void;
  clearHistory: () => void;
  
  // 设置
  setPickerMode: (mode: ColorPickerMode) => void;
  clearError: () => void;
  
  // 工具方法
  generateRandomPalette: (count?: number) => void;
  importColors: (colors: string[]) => void;
  exportPalette: (format: 'json' | 'css' | 'sass') => string;
}

// 默认颜色
const defaultColor: Color = ColorUtils.fromHex('#3B82F6');

/**
 * 色彩状态管理 Store
 */
export const useColorStore = create<ColorState>()(
  persist(
    (set, get) => ({
      // 初始状态
      currentColor: defaultColor,
      selectedColors: [],
      activePalette: null,
      pickerMode: 'simple',
      isLoading: false,
      error: null,
      colorHistory: [],
      recentSchemes: [],

      // 设置当前颜色
      setCurrentColor: (colorInput: Color | string) => {
        try {
          const color = typeof colorInput === 'string' 
            ? ColorUtils.fromHex(colorInput) 
            : colorInput;
          
          set({ currentColor: color, error: null });
          
          // 添加到历史记录
          get().addToHistory(color);
        } catch (error) {
          set({ error: '无效的颜色格式' });
        }
      },

      // 添加选中的颜色
      addSelectedColor: (color: Color) => {
        const { selectedColors } = get();
        const maxColors = 10; // 最大颜色数量限制
        
        if (selectedColors.length >= maxColors) {
          set({ error: `最多只能选择 ${maxColors} 种颜色` });
          return;
        }
        
        // 检查是否已存在相同颜色
        const exists = selectedColors.some(c => c.hex === color.hex);
        if (exists) {
          set({ error: '该颜色已存在于调色板中' });
          return;
        }
        
        set({ 
          selectedColors: [...selectedColors, color],
          error: null
        });
      },

      // 移除选中的颜色
      removeSelectedColor: (index: number) => {
        const { selectedColors } = get();
        if (index >= 0 && index < selectedColors.length) {
          const newColors = selectedColors.filter((_, i) => i !== index);
          set({ selectedColors: newColors });
        }
      },

      // 更新选中的颜色
      updateSelectedColor: (index: number, color: Color) => {
        const { selectedColors } = get();
        if (index >= 0 && index < selectedColors.length) {
          const newColors = [...selectedColors];
          newColors[index] = color;
          set({ selectedColors: newColors });
        }
      },

      // 清空选中的颜色
      clearSelectedColors: () => {
        set({ selectedColors: [] });
      },

      // 创建调色板
      createPalette: async (name: string, type: ColorSchemeType) => {
        const { selectedColors } = get();
        
        if (selectedColors.length === 0) {
          throw new Error('请至少选择一种颜色');
        }
        
        set({ isLoading: true, error: null });
        
        try {
          const palette: ColorScheme = {
            id: generateId(),
            name,
            colors: selectedColors,
            type,
            createdAt: new Date(),
            updatedAt: new Date(),
            tags: [],
            isFavorite: false
          };
          
          await StorageService.saveColorScheme(palette);
          
          // 更新最近方案
          const { recentSchemes } = get();
          const newRecentSchemes = [palette, ...recentSchemes.slice(0, 9)];
          
          set({ 
            activePalette: palette,
            recentSchemes: newRecentSchemes,
            isLoading: false 
          });
          
          return palette;
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : '创建调色板失败',
            isLoading: false 
          });
          throw error;
        }
      },

      // 加载调色板
      loadPalette: (palette: ColorScheme) => {
        set({ 
          activePalette: palette,
          selectedColors: palette.colors,
          currentColor: palette.colors[0] || defaultColor
        });
      },

      // 保存调色板
      savePalette: async (palette: ColorScheme) => {
        set({ isLoading: true, error: null });
        
        try {
          await StorageService.saveColorScheme(palette);
          set({ 
            activePalette: palette,
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : '保存调色板失败',
            isLoading: false 
          });
          throw error;
        }
      },

      // 删除调色板
      deletePalette: async (id: string) => {
        set({ isLoading: true, error: null });
        
        try {
          await StorageService.deleteColorScheme(id);
          
          const { activePalette, recentSchemes } = get();
          
          // 如果删除的是当前活动调色板，清空
          if (activePalette?.id === id) {
            set({ activePalette: null });
          }
          
          // 从最近方案中移除
          const newRecentSchemes = recentSchemes.filter(s => s.id !== id);
          
          set({ 
            recentSchemes: newRecentSchemes,
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : '删除调色板失败',
            isLoading: false 
          });
          throw error;
        }
      },

      // 添加到历史记录
      addToHistory: (color: Color) => {
        const { colorHistory } = get();
        const maxHistory = 50; // 最大历史记录数量
        
        // 检查是否已存在
        const existingIndex = colorHistory.findIndex(c => c.hex === color.hex);
        
        let newHistory: Color[];
        
        if (existingIndex >= 0) {
          // 如果存在，移动到最前面
          newHistory = [
            color,
            ...colorHistory.filter((_, i) => i !== existingIndex)
          ];
        } else {
          // 如果不存在，添加到最前面
          newHistory = [color, ...colorHistory];
        }
        
        // 限制历史记录数量
        newHistory = newHistory.slice(0, maxHistory);
        
        set({ colorHistory: newHistory });
      },

      // 清空历史记录
      clearHistory: () => {
        set({ colorHistory: [] });
      },

      // 设置选择器模式
      setPickerMode: (mode: ColorPickerMode) => {
        set({ pickerMode: mode });
      },

      // 清除错误
      clearError: () => {
        set({ error: null });
      },

      // 生成随机调色板
      generateRandomPalette: (count: number = 5) => {
        const colors: Color[] = [];
        
        for (let i = 0; i < count; i++) {
          colors.push(ColorUtils.randomColor());
        }
        
        set({ 
          selectedColors: colors,
          currentColor: colors[0]
        });
      },

      // 导入颜色
      importColors: (hexColors: string[]) => {
        try {
          const colors = hexColors
            .filter(hex => ColorUtils.isValidHex(hex))
            .map(hex => ColorUtils.fromHex(hex));
          
          if (colors.length === 0) {
            set({ error: '没有有效的颜色格式' });
            return;
          }
          
          set({ 
            selectedColors: colors,
            currentColor: colors[0],
            error: null
          });
        } catch (error) {
          set({ error: '导入颜色失败' });
        }
      },

      // 导出调色板
      exportPalette: (format: 'json' | 'css' | 'sass') => {
        const { selectedColors, activePalette } = get();
        const colors = selectedColors;
        
        if (colors.length === 0) {
          throw new Error('没有可导出的颜色');
        }
        
        switch (format) {
          case 'json':
            return JSON.stringify({
              name: activePalette?.name || 'Untitled Palette',
              colors: colors.map(c => ({
                hex: c.hex,
                rgb: c.rgb,
                hsl: c.hsl,
                name: c.name
              }))
            }, null, 2);
            
          case 'css':
            return `:root {\n${colors.map((c, i) => 
              `  --color-${i + 1}: ${c.hex};`
            ).join('\n')}\n}`;
            
          case 'sass':
            return colors.map((c, i) => 
              `$color-${i + 1}: ${c.hex};`
            ).join('\n');
            
          default:
            throw new Error('不支持的导出格式');
        }
      }
    }),
    {
      name: 'color-store',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        currentColor: state.currentColor,
        selectedColors: state.selectedColors,
        activePalette: state.activePalette,
        pickerMode: state.pickerMode,
        colorHistory: state.colorHistory,
        recentSchemes: state.recentSchemes
      })
    }
  )
);